#!/usr/bin/python2.5
# Nobody owns this script, most of the code is already stolen
# from YouLoc users

import time
import sys
import httplib, urllib

## Settings
# how often the location should be sent? (in seconds)
updateInterval = 5;
# user-key is temporarily your IMEI/other given identity
user_key = "<your imei here>"
# this is the device where you have bound your gps
# it could be:
# /dev/pgps in nokia internet tablet N810
# /dev/rfcomm0 if you have bound it yourself
# /dev/something ;) play around with it, mmkay?
gps_device = "/dev/tty.gps"


version = 0.25
print "YouLocPython v%0.2f" % (version)


lastLat = None
lastLong = None
lastTime = time.time() - 100
connected = 0


def postData(time,lat,long):
	conn = httplib.HTTPConnection("proto.youloc.net:80")
	url = "/logger.php?imei=%s&time=%s&lat=%s&lon=%s" % (user_key, time, lat, long)
	conn.request("GET", url)
	response = conn.getresponse()
	data = response.read()
 	conn.close()

def parseData(data):
        d = data.split( ',' )
        
        return (d[1], d[2],d[3], d[4],d[5] )

sys.stdout.write("Connecting.")

f = open(gps_device)
try:
	for data in f:
		if (connected == 0):
			sys.stdout.write(".")
		if( data[0:6] == '$GPGGA' ):
			(utc,latitude, northsouth, longitude, eastwest) = parseData( data )
			curTime = time.time()
			if( latitude != "" and longitude != "" and ( latitude != lastLat or longitude !=lastLong ) and curTime > lastTime + updateInterval):
				if (connected == 0 ):
					print ".done"
					connected = 1
				latitude_in=float(latitude)
				longitude_in=float(longitude)
				if northsouth == 'S':
					latitude_in = -latitude_in
				if eastwest == 'W':
					longitude_in = -longitude_in
		
				latitude_degrees = int(latitude_in/100)
				latitude_minutes = latitude_in - latitude_degrees*100
				
				longitude_degrees = int(longitude_in/100)
				longitude_minutes = longitude_in - longitude_degrees*100
				
				latitude = latitude_degrees + (latitude_minutes/60)
				longitude = longitude_degrees + (longitude_minutes/60)
				
				timeOfFix = time.strftime("%H:%M:%S", time.strptime(utc.split(".")[0],"%H%M%S"))
				lastLat = latitude
				lastLong = longitude
				lastTime = curTime
				postData(curTime,latitude,longitude)
				print "POSTED %s, %s" % (latitude, longitude)


finally:
	f.close()
